﻿using ChessTest.Chess.Items;
using org.xisoft.game.utils.game;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ChessTest.Chess.Algorithms
{
    /// <summary>
    /// alphabeta算法
    /// </summary>
    class AlphaBetaAlgorithm : AiAlgorithm
    {
        private readonly int MATE = 60000;

        public override MoveAction Search(AiChessboard aiChessboard, int depth)
        {

            return AlphaBetaSearch(aiChessboard, depth, -MATE, MATE);
        }


        private MoveAction AlphaBetaSearch(AiChessboard aiChessboard,int depth, long alpha, long beta)
        {

            MoveAction bestChildstep = null;


            List<MoveAction> canMoveActionList = GetAllCanMoves(aiChessboard);
            foreach (MoveAction action in canMoveActionList)
            {
                MoveAction step = null;
                if (depth > 0)
                {
                    aiChessboard.DoNextMove(action);

                    if (ContainsHistory(aiChessboard))
                    {
                        aiChessboard.Undo();
                        continue;
                    }



                    step = AlphaBetaSearch(aiChessboard,depth - 1, -beta, -alpha);
                    aiChessboard.Undo();
                }

                if(step!=null)
                action.Score -= step.Score;

                if (bestChildstep == null || bestChildstep.Score < action.Score)
                    bestChildstep = action;
                    



                if (bestChildstep.Score > alpha)
                    alpha = bestChildstep.Score;

                //这个少了一个等号，结果就和maxmin算法结果一致
                if (bestChildstep.Score >= beta)
                {
                    break;
                }

            }



            if (bestChildstep == null)
            {
                //被将死了，无子可走,
                bestChildstep = new MoveAction() { Score = -1000 - depth * 10 };
            }

            return bestChildstep;
        }
    }



}
